﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>用户管理</title>
    <link rel="stylesheet" href="../../assets/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="../../assets/module/admin.css?v=318"/>
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script type="text/javascript" src="../../assets/js/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="../../assets/js/config.js"></script>
    <script type="text/javascript" src="../../assets/js/auth.js"></script>
</head>
<body>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 表格工具栏 -->
            <form class="layui-form toolbar" id="searchData">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">账&emsp;号:</label>
                        <div class="layui-input-inline">
                            <input name="username" class="layui-input" placeholder="输入账号"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">用户名:</label>
                        <div class="layui-input-inline">
                            <input name="nickname" class="layui-input" placeholder="输入用户名"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">性&emsp;别:</label>
                        <div class="layui-input-inline">
                            <select name="gender">
                                <option value="">选择性别</option>
                                <option value="1">男</option>
                                <option value="0">女</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">&emsp;
                        <button class="layui-btn icon-btn" lay-filter="userTbSearch" lay-submit>
                            <i class="layui-icon">&#xe615;</i>搜索
                        </button>
                    </div>
                    <div class="layui-inline">&emsp;
                        <button class="layui-btn icon-btn layui-btn-danger" lay-filter="userTbClear" lay-submit>
                            <i class="layui-icon">&#xe666;</i>清空
                        </button>
                    </div>
                </div>
            </form>
            <!-- 数据表格 -->
            <table id="userTable" lay-filter="userTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="userTbBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="reset">重置密码</a>
</script>
<!-- 表格状态列 -->
<script type="text/html" id="userTbState">
    <input type="checkbox" lay-filter="userTbStateCk" value="{{d.id}}" lay-skin="switch"
           lay-text="正常|锁定" {{d.status==0?'checked':''}} style="display: none;"/>
    <p style="display: none;">{{d.state==0?'正常':'锁定'}}</p>
</script>
<!-- 表格性别列 -->
<script type="text/html" id="userTbgender">
    <p>{{d.gender==0?'女':'男'}}</p>
</script>



<!-- 表单弹窗 -->
<script type="text/html" id="userEditDialog">
    <form id="userEditForm" lay-filter="userEditForm" class="layui-form model-form">
        <input name="userId" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">账号:</label>
            <div class="layui-input-block">
                <input name="id" type="hidden">
                <input name="username" placeholder="请输入账号" class="layui-input"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">用户名:</label>
            <div class="layui-input-block">
                <input name="nickname" placeholder="请输入用户名" class="layui-input"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">性别:</label>
            <div class="layui-input-block">
                <input type="radio" name="gender" value="1" title="男" checked/>
                <input type="radio" name="gender" value="0" title="女"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">手机号:</label>
            <div class="layui-input-block">
                <input name="mobile" placeholder="请输入手机号" class="layui-input"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">角色:</label>
            <div class="layui-input-block">
                <div id="userEditRoleSel"></div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="userEditSubmit" lay-submit>保存</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script type="text/javascript" src="../../assets/libs/layui/layui.js"></script>
<script type="text/javascript" src="../../assets/js/common.js?v=318"></script>
<script>
    // 角色列表
    const roleList=[];

    layui.use(['layer', 'form', 'table', 'util', 'admin', 'xmSelect'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;
        var admin = layui.admin;
        var xmSelect = layui.xmSelect;
        var count=0;
        var intab="";
        getRole();
        function getRole(){
            $.ajax({
                type: 'get',
                url: basePath+'/admin/roles/roleIndex',
                dataType: 'json',
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("token", auth.token);
                },
                success: function (res) {
                    if(res.code=="00000"){
                        var roles=res.data;
                        for(var i=0;i<roles.length;i++){
                            var role={value:roles[i].id,name:roles[i].name};
                            roleList.push(role);
                        }
                    }
                }
            });
        };

        //渲染表格
        var renderTable = function () {
            layer.load(2);
            let requestData={"nickname":'',"gender":'',"username":'',"page":1,"limit":10};
            $.ajax({
                type: 'get',
                url: basePath+'/admin/users',
                data: requestData,
                dataType: 'json',
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("token", auth.token);
                },
                success: function (res) {
                    count=res.total;
                    renderTable(res.data);
                }
            });

            // 渲染表格
            var renderTable = function (data) {
                layer.load(2);
                intab=table.render({
                    elem: '#userTable',
                    url: basePath+'/admin/users',
                    toolbar: ['<p>',
                        '<button lay-event="add" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>&nbsp;',
                        '<button lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger icon-btn"><i class="layui-icon">&#xe640;</i>删除</button>',
                        '</p>'].join(''),
                    cellMinWidth: 100,
                    page: true,
                    cols: [[
                        {type: 'checkbox'},
                        {field: 'id',title: '编号'},
                        {field: 'username', title: '账号', sort: true},
                        {field: 'nickname', title: '用户名', sort: true},
                        {field: 'gender', templet: '#userTbgender', title: '性别', sort: true},
                        {field: 'mobile', title: '手机号', sort: true},
                        {
                            field: 'name', title: '角色', templet: function (d) {
                                return d.roles.map(function (item) {
                                    return '<span class="layui-badge layui-badge-gray">' + item.name + '</span>';
                                }).join('&nbsp;&nbsp;');
                            }, sort: true, width: 150
                        },
                        {
                            field: 'gmtCreate', title: '创建时间', templet: function (d) {
                                return util.toDateString(d.gmtCreate);
                            }, sort: true
                        },
                        {field: 'status', title: '状态', templet: '#userTbState', sort: true, width: 100},
                        {title: '操作', toolbar: '#userTbBar', align: 'center', minWidth: 200}
                    ]]
                    //数据渲染完的回调
                    ,done: function () {
                        //清空本地记录的 token，并跳转到登入页
                        layer.closeAll('loading');
                    }
                })
            }
        };

        renderTable();

        /* 表格搜索 */
        form.on('submit(userTbSearch)', function (data) {
            intab.reload({where: data.field, page: {curr: 1}});
            return false;
        });

        /* 表格清空*/
        form.on('submit(userTbClear)', function (data) {
           $("#searchData")[0].reset();
            intab.reload({where: data.field, page: {curr: 1}});
            return false;
        });

        /* 表格工具条点击事件 */
        table.on('tool(userTable)', function (obj) {
            if (obj.event === 'edit') { // 修改
                showEditModel(obj.data);
            } else if (obj.event === 'del') { // 删除
                doDel(obj);
            } else if (obj.event === 'reset') { // 重置密码
                resetPsw(obj);
            }
        });

        /* 表格头工具栏点击事件 */
        table.on('toolbar(userTable)', function (obj) {
            if (obj.event === 'add') { // 添加
                showEditModel();
            } else if (obj.event === 'del') { // 删除
                var checkRows = table.checkStatus('userTable');
                if (checkRows.data.length === 0) {
                    layer.msg('请选择要删除的数据', {icon: 2});
                    return;
                }
                var ids = checkRows.data.map(function (d) {
                    return d.userId;
                });
                doDel({ids: ids});
            }
        });

        /* 显示表单弹窗 */
        function showEditModel(mData) {
            admin.open({
                type: 1,
                title: (mData ? '修改' : '添加') + '用户',
                skin: 'layui-layer-rim', //加上边框
                content: $('#userEditDialog').html(),
                success: function (layero, dIndex) {
                    // 回显表单数据
                    form.val('userEditForm', mData);
                    // 表单提交事件
                    form.on('submit(userEditSubmit)', function (data) {
                       data.field.roleIds = insRoleSel.getValue('valueStr');
                       var loadIndex = layer.load(2);
                       var roleIds=data.field.roleIds;
                       if(roleIds!=null && roleIds!=''){
                           $.ajax({
                               type: "post",
                               url: basePath + '/admin/users',
                               data: data.field,
                               async: false,
                               dataType: "json",
                               //这里是重点
                               beforeSend: function (XMLHttpRequest) {
                                   XMLHttpRequest.setRequestHeader("token", auth.token);
                               },
                               success: function (res) {
                                   if(res.code=="00000"){
                                       layer.msg(res.msg, {icon: 1});
                                       intab.reload({where: '', page: {curr: 1}});
                                   }else{
                                       layer.msg(res.msg, {icon: 2});
                                   }
                                   layer.close(dIndex);
                               },
                               error: function (error) {
                                   console.log(error);
                               }
                           });
                       }else{
                           layer.msg("用户角色不可为空", {icon: 2});
                       }

                        layer.close(loadIndex);
                        return false;
                    });

                    // 渲染多选下拉框
                    var insRoleSel = xmSelect.render({
                        el: '#userEditRoleSel',
                        name: 'userEditRoleSel',
                        layVerify: 'required',
                        layVerType: 'tips',
                        data: roleList
                    });

                    // 回显选中角色
                    if (mData && mData.roles) {
                        insRoleSel.setValue(mData.roles.map(function (item) {
                            return item.id;
                        }));
                    }
                    // 禁止弹窗出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        }

        /* 删除 */
        function doDel(obj) {
            layer.confirm('确定要删除选中数据吗？', {
                skin: 'layui-layer-admin',
                shade: .1
            }, function (i) {
                layer.close(i);
                var loadIndex = layer.load(2);
                let requestData={id: obj.data.id, del:'1',status:''};
                $.ajax({
                    type: "post",
                    url: basePath + '/admin/users/upStatus/',
                    data: requestData,
                    async: false,
                    dataType: "json",
                    //这里是重点
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("token", auth.token);
                    },
                    success: function (res) {
                        layer.msg(res.msg, {icon: 1});
                        if(res.code=="00000"){
                            intab.reload({page: {curr: 1}});
                        }
                    }, error: function (e) {
                        layer.msg("请求出错啦，请联系管理员!", {icon: 2});
                    }
                });
                layer.close(loadIndex);
        });
    }
        /* 修改用户状态 */
        form.on('switch(userTbStateCk)', function (obj) {
            let stat=obj.elem.checked ? 0 : 1;
            let id=obj.elem.value
            let requestData={id: id, del:'',status: stat};
            $.ajax({
                type: "post",
                url: basePath + '/admin/users/upStatus/',
                data: requestData,
                async: false,
                dataType: "json",
                //这里是重点
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("token", auth.token);
                },
                success: function (res) {
                    layer.msg(res.msg, {icon: 1});
                    if(res.code=="00000"){
                        intab.reload({page: {curr: 1}});
                    }else{
                        layer.msg(res.msg, {icon: 2});
                        $(obj.elem).prop('checked', !obj.elem.checked);
                        form.render('checkbox');
                    }
                }, error: function (e) {
                    layer.msg("请求出错啦，请联系管理员!", {icon: 2});
                }
            });
        });

        /* 重置密码 */
        function resetPsw(obj) {
            layer.confirm('确定要重置账号【' + obj.data.username + '】的登录密码吗？', {
                skin: 'layui-layer-admin',
                shade: .1
            }, function (i) {
                layer.close(i);
                var loadIndex = layer.load(2);
                let requestData={username: obj.data.username};
                console.log("查询参数："+requestData);
                $.ajax({
                    type: "post",
                    url: basePath + '/admin/users/change/',
                    data: requestData,
                    async: false,
                    dataType: "json",
                    //这里是重点
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("token", auth.token);
                    },
                    success: function (res) {
                        layer.msg(res.msg, {icon: 1});
                        if(res.code=="00000"){
                            intab.reload({page: {curr: 1}});
                        }
                    }, error: function (e) {
                        layer.msg("请求出错啦，请联系管理员!", {icon: 2});
                    }
                });
                layer.close(loadIndex);
            });
        }

    });
</script>
</body>
</html>
